#include "../engine/core.h"
#include "LoginMsgHandler.h"
#include "../engine/ComputureMgr.h"
#include "../engine/Protocal/Common.pb.h"
#include "../engine/AsioTcpLink.h"
#include "../engine/AsioTcpLinkClient.h"
#include "../engine/GlobalConfig.h"
#include "../engine/ServerCore.h"
#include "../engine/Misc.h"
#include "../engine/LogMgr.h"
#include "../engine/UserMgr.h"
#include "../engine/DbExecute.h"

IMP_SINGLETON_CLASS(CLoginMsgHandler)

CLoginMsgHandler::CLoginMsgHandler()
{
	Reg();
}

CLoginMsgHandler::~CLoginMsgHandler()
{
	UnReg();
}

void CLoginMsgHandler::UnReg()
{
	CPacketProcesser* processer = CPacketProcesser::getInstance();
	if (processer)
	{
		processer->UnReg(MYTH::CMD_User_Login);
		processer->UnReg(MYTH::CMD_User_Login_r);
		processer->UnReg(MYTH::CMD_User_Reg);
	}
}

void CLoginMsgHandler::Reg()
{
	CPacketProcesser* processer = CPacketProcesser::getInstance();
	if (processer)
	{
		processer->RegCB(MYTH::CMD_User_Login, boost::BOOST_BIND(&CLoginMsgHandler::OnUserLogin, this, _1));
		processer->RegCB(MYTH::CMD_User_Login_r, boost::BOOST_BIND(&CLoginMsgHandler::OnUserLogin_r, this, _1));
		processer->RegCB(MYTH::CMD_User_Reg, boost::BOOST_BIND(&CLoginMsgHandler::OnUserReg, this, _1));
	}
}

void CLoginMsgHandler::OnUserLogin(xMSG& msg)
{
	net_link_ptr link_ptr = boost::dynamic_pointer_cast<CAsioTcpLink>(xNetObjBase::getNetObj(msg.call_guid));
	if (link_ptr.get())
	{
		MYTH::AccountLogin UserLogin;
		if (UserLogin.ParseFromArray(msg.getParameterData(), msg.getParameterSize()))
		{
			CUserMgr* pUserMgr = CUserMgr::getInstance();
			CServerCore* pServerCore = CServerCore::getInstance();
			pUserMgr->AddLoginUser(UserLogin.account_id(),link_ptr.get());

			pServerCore->SendMsg2Server(ENetDef::NET_GAME_DB, msg);
		}
	}
}

void CLoginMsgHandler::OnUserLogin_r(xMSG& msg)
{
	CUserMgr* pUserMgr = CUserMgr::getInstance();
	CServerCore* pServerCore = CServerCore::getInstance();
	MYTH::AccountLogin_R r;
	if (r.ParseFromArray(msg.getParameterData(), msg.getParameterSize()))
	{
	}
}

void CLoginMsgHandler::OnUserReg(xMSG& msg)
{
	net_link_ptr link_ptr = boost::dynamic_pointer_cast<CAsioTcpLink>(xNetObjBase::getNetObj(msg.call_guid));
	if (link_ptr.get())
	{
		MYTH::AccountReg UserReg;
		if (UserReg.ParseFromArray(msg.getParameterData(), msg.getParameterSize()))
		{
			char sql[1024];
			CDbExecute db;
			sprintf_s(sql,"call new_user('%s', '%s', '%s')", UserReg.account_id().c_str(), UserReg.account_pwd().c_str(), link_ptr->getRemoteIP());
			db.execute(sql);

	//		CServerCore* pCore = CServerCore::getInstance();
			MYTH::AccountReg_R r;
			r.set_err_code(db.getResult() == "SUCCESS" ? MYTH::Error_Success : MYTH::Error_HaveUser);
			U64 uUser_id = 0;
			if (db.GetRowMap().GetValueU64("guid", uUser_id))
			{
				r.set_user_id(uUser_id);
			}
			xMSG rl(MYTH::CMD_User_Reg_r, &r);
			link_ptr->prepWrite(rl.msg_ptr, rl.dwLen);
		}
	}
}
